const uniID = require('uni-id-common');
const db = uniCloud.database();
exports.main = async (event, context) => {
  const _ = db.command;
  const uniIDIns = uniID.createInstance({ context });
  
  let body = event;
  if (event.body != undefined) {
    body = JSON.parse(event.body);
  }

  try {
    // 1. 身份验证
    const { uid } = await uniIDIns.checkToken(body.uniIdToken);
    if (!uid) {
      return { 
        code: 403, 
        success: false,
        message: "身份验证失败",
        details: "提供的uniIdToken无效或已过期"
      };
    }

    // 2. 参数校验
    const { day, freeSlot } = body;
    
    if (!day) {
      return {
        code: 400,
        success: false,
        message: "缺少必要参数",
        details: "必须提供day参数"
      };
    }
    
    if (!freeSlot) {
      return {
        code: 400,
        success: false,
        message: "缺少必要参数",
        details: "必须提供freeSlot参数"
      };
    }

    // 3. 日期格式校验
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
    if (!dateRegex.test(day)) {
      return {
        code: 400,
        success: false,
        message: "参数格式错误",
        details: "day参数格式应为YYYY-MM-DD"
      };
    }
	//日期有效性校验
	const dateObj = new Date(day);
	if (isNaN(dateObj.getTime())) {
	    return {
	        success: false,
	        code: 400,
	        message: "提供的日期无效"
	    };
	}
	
    // 4. 时间段格式校验
    const timeSlotRegex = /^([01]?[0-9]|2[0-3]):00-([01]?[0-9]|2[0-3]):50$/;
    if (!timeSlotRegex.test(freeSlot)) {
      return {
        code: 400,
        success: false,
        message: "时间段格式错误",
        details: "必须为整点开始、50分钟结束的区间，例如: 09:00-09:50"
      };
    }

    // 解析时间段
    const [startTime, endTime] = freeSlot.split('-');
    const [startHour, startMinute] = startTime.split(':').map(Number);
    const [endHour, endMinute] = endTime.split(':').map(Number);

    // 检查时间跨度是否为50分钟
    const startTotalMinutes = startHour * 60 + startMinute;
    const endTotalMinutes = endHour * 60 + endMinute;
    
    if (endTotalMinutes - startTotalMinutes !== 50) {
      return {
        code: 400,
        success: false,
        message: "时间段格式错误",
        details: "必须为整点开始、50分钟结束的区间，例如: 09:00-09:50"
      };
    }

    // 5. 查询原始记录
    const recordQuery = await db.collection('consultant_schedule')
      .where({
        user: uid,
        day: day
      })
      .get();
      
    if (recordQuery.data.length === 0) {
      return {
        code: 404,
        success: false,
        message: "未找到预约记录",
      };
    }

    const currentFreeSlots = recordQuery.data[0].freeSlots || [];
    if (!currentFreeSlots.includes(freeSlot)) {
      return {
        code: 400,
        success: false,
        message: "操作无效",
        details: `时间段${freeSlot}不在可取消的时间段列表中`
      };
    }

    // 6. 更新操作
    const updateRes = await db.collection('consultant_schedule')
      .where({
        user: uid,
        day: day,
      })
      .update({
        freeSlots: _.pull(freeSlot)
      });

    if (updateRes.updated === 0) {
      return {
        code: 500,
        success: false,
        message: "更新失败",
        details: "数据库更新操作未影响任何记录"
      };
    }
	
	// 删除匹配记录（uid + day + appointedSlot）
	const res = await db.collection('appoint_schedule')
	  .where({
	    consultant: uid,
	    day: day,
	    appointedSlot: freeSlot
	  })
	  .remove();

    // 7. 检查是否为空，如果是则删除记录
    const updatedRecord = await db.collection('consultant_schedule')
      .where({
        user: uid,
        day: day,
      })
      .get();
	  

    const remainingSlots = updatedRecord.data[0].freeSlots || [];
    if (remainingSlots.length === 0) {
      await db.collection('consultant_schedule')
        .where({
          user: uid,
          day: day,
        })
        .remove();
        
      return {
        code: 200,
        success: true,
        message: "已取消最后一个空闲时段，记录已删除"
      };
    }

    return {
      code: 200,
      success: true,
      message: "已成功取消指定空闲时段",
      remainingSlots: remainingSlots
    };

  } catch (error) {
    console.error("取消空闲时段失败:", error);
    return {
      code: 500,
      success: false,
      message: "服务器内部错误",
      details: process.env.NODE_ENV === 'development' ? error.message : undefined,
    };
  }
};